package com.smart.stock.module.spider.jobSpiderApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.stock.module.GlobalConstant;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class EastmoneyApi {
    String api = "http://push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery112403145934441741707_1627057927609&secid=1.000001&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58&klt=101&fqt=0&beg=19900101&end=20220101&_=1627057927619";

    String post(JSONObject params) {
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        params.put("token", GlobalConstant.TOKEN_EASTMONEY);
        HttpEntity<String> formEntity = new HttpEntity<String>(params.toString(), headers);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(api, formEntity, String.class);
        return result;
    }
//    public JSONArray getIndexDaily(String code, String startDate, String endDate){
    public JSONArray getIndexDaily(){
        JSONObject json = new JSONObject();
//        JSONObject params = new JSONObject();
//        params.put("ts_code", code);
//        params.put("start_date", startDate);
//        params.put("end_date", endDate);
//        //接口名称
//        json.put("api_name", "index_daily");
//        json.put("params", params);
//        json.put("fields","ts_code,trade_date,close,open,high,low");
        String result = post(json);
//        jQuery112403145934441741707_1627057927609()
        result = result.substring(result.indexOf("(")+1,result.length()-2);



        JSONObject datas = JSON.parseObject(result);

        JSONArray items = datas.getJSONObject("data").getJSONArray("klines");
        return items;
    }

    public static void main(String[] args) {

        EastmoneyApi api = new EastmoneyApi();
        api.getIndexDaily();
    }
}
